/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import 'vs/css!vs/workbench/contrib/wechat/browser/media/wechat';

import { DisposableStore } from 'vs/base/common/lifecycle';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane';
import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { IHoverService } from 'vs/platform/hover/browser/hover';
import { IAccessibleViewInformationService } from 'vs/workbench/services/accessibility/common/accessibleViewInformationService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { WechatEditorInput, WechatUser } from 'vs/workbench/contrib/wechat/browser/wechatEditorInput';
import { WechatEditor } from 'vs/workbench/contrib/wechat/browser/wechatEditor';


export class WechatViewPane extends ViewPane {
	static readonly ID = 'workbench.view.wechat';

	private readonly _disposables = new DisposableStore();
	private readonly _sessionDisposables = new DisposableStore();
	private _container!: HTMLElement;
	private _selectedUserElement: HTMLElement | undefined;

	// 模拟聊天用户数据
	private readonly _users: WechatUser[] = [
		{ name: '阿莲', status: 'online', avatar: 'A' },
		{ name: '张三', status: 'offline', avatar: 'Z' },
		{ name: '李四', status: 'online', avatar: 'L' },
		{ name: '王五', status: 'away', avatar: 'W' }
	];

	constructor(
		options: IViewletViewOptions,
		@IKeybindingService keybindingService: IKeybindingService,
		@IContextMenuService contextMenuService: IContextMenuService,
		@IConfigurationService configurationService: IConfigurationService,
		@IContextKeyService contextKeyService: IContextKeyService,
		@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
		@IInstantiationService protected override readonly instantiationService: IInstantiationService,
		@IOpenerService openerService: IOpenerService,
		@IThemeService themeService: IThemeService,
		@ITelemetryService telemetryService: ITelemetryService,
		@IHoverService hoverService: IHoverService,
		@IAccessibleViewInformationService accessibleViewInformationService: IAccessibleViewInformationService,
		@IEditorService private readonly editorService: IEditorService
	) {
		super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService, accessibleViewInformationService);
	}

	protected override renderBody(container: HTMLElement): void {
		super.renderBody(container);

		this._container = container;
		this._container.classList.add('wechat-view');

		// 添加一个简单的用户列表
		const userListContainer = document.createElement('div');
		userListContainer.className = 'wechat-user-list';

		// 绘制每个用户
		this._users.forEach(user => {
			const userItem = this.createUserItem(user);
			userListContainer.appendChild(userItem);
		});

		// 添加到容器
		this._container.appendChild(userListContainer);
	}

	/**
	 * 创建用户列表项
	 */
	private createUserItem(user: WechatUser): HTMLElement {
		const userItem = document.createElement('div');
		userItem.className = 'wechat-user-item';
		userItem.setAttribute('data-status', user.status);
		userItem.setAttribute('data-username', user.name);

		const avatar = document.createElement('div');
		avatar.className = 'wechat-user-avatar';
		avatar.textContent = user.avatar;

		const userName = document.createElement('div');
		userName.className = 'wechat-user-name';
		userName.textContent = user.name;

		const statusIndicator = document.createElement('div');
		statusIndicator.className = 'wechat-user-status';

		userItem.appendChild(avatar);
		userItem.appendChild(userName);
		userItem.appendChild(statusIndicator);

		// 添加点击事件
		userItem.addEventListener('click', () => {
			// 移除之前的选中状态
			if (this._selectedUserElement) {
				this._selectedUserElement.classList.remove('selected');
			}

			// 添加新的选中状态
			userItem.classList.add('selected');
			this._selectedUserElement = userItem;

			// 打开用户聊天
			this.openUserChat(user);
		});

		return userItem;
	}

	/**
	 * 打开用户聊天窗口
	 */
	private openUserChat(user: WechatUser): void {
		// 深度复制用户对象以避免引用问题
		const selectedUser: WechatUser = {
			name: user.name,
			status: user.status,
			avatar: user.avatar
		};

		console.log('[WechatViewPane] Opening chat with user:', selectedUser.name);

		// 直接设置最后选择的用户，确保编辑器始终使用这个用户
		WechatEditor.setLastSelectedUser(selectedUser);

		// 首先检查是否已有打开的WeChat编辑器
		const activeEditorPane = this.editorService.activeEditorPane;

		// 如果当前已有活跃的WeChat编辑器
		if (activeEditorPane?.input instanceof WechatEditorInput) {
			console.log('[WechatViewPane] 已有活跃WeChat编辑器，强制替换用户:', selectedUser.name);
			const input = activeEditorPane.input as WechatEditorInput;

			// 更新编辑器的用户
			input.setSelectedUser(selectedUser);

			// 即使编辑器已经是活跃的，也重新打开一次，这可以触发编辑器的setInput
			this.editorService.openEditor(input, {
				pinned: true,
				preserveFocus: false // 确保编辑器获得焦点
			});
			return;
		}

		// 如果没有活跃的编辑器，查找所有打开的WeChat编辑器
		const allEditorGroups = this.editorService.visibleEditorPanes;
		for (const editorPane of allEditorGroups) {
			if (editorPane?.input instanceof WechatEditorInput) {
				console.log('[WechatViewPane] 找到已打开的WeChat编辑器，强制替换用户:', selectedUser.name);
				const input = editorPane.input as WechatEditorInput;

				// 强制替换用户
				input.setSelectedUser(selectedUser);

				// 激活编辑器
				this.editorService.openEditor(input, {
					pinned: true,
					preserveFocus: false // 确保编辑器获得焦点
				});
				return;
			}
		}

		// 如果没有找到任何WeChat编辑器，创建新的
		console.log('[WechatViewPane] 创建新的WeChat编辑器:', selectedUser.name);
		const editorInput = this.instantiationService.createInstance(WechatEditorInput, selectedUser);
		this.editorService.openEditor(editorInput, {
			pinned: true,
			preserveFocus: false // 确保编辑器获得焦点
		});
	}

	protected override layoutBody(height: number, width: number): void {
		super.layoutBody(height, width);
	}

	override dispose(): void {
		this._disposables.dispose();
		this._sessionDisposables.dispose();
		super.dispose();
	}
}
